//
//  RPDBManage.m
//  renphoApp
//
//  Created by Simon on 2020/11/6.
//

#import "RPDBManage.h"

/**
 声明方法,是为了调用FMDatabase私有方法
 */
@interface FMDatabase ()
/*
- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;*/

@end

/**
 db升级到dbQueue,兼容旧代码
 */
/*
@implementation RPDatabaseQueue

- (BOOL)open {
    return [[self db] open];
}

- (BOOL)executeUpdate:(NSString *)sql, ... {
    va_list args;
    va_start(args, sql);
    
    __block BOOL result = NO;
    [self inDatabase:^(FMDatabase *_Nonnull db) {
        result = [db executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
    }];
    
    va_end(args);
    return result;
}

- (FMResultSet *)executeQuery:(NSString *)sql, ... {
    va_list args;
    va_start(args, sql);
    
    __block FMResultSet *resultSet = nil;
    [self inDatabase:^(FMDatabase *_Nonnull db) {
        RPLog(LogAction, @"【quey】%@", sql);
        resultSet = [db executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
    }];
    
    va_end(args);
    return resultSet;
}

- (BOOL)columnExists:(NSString *)columnName inTableWithName:(NSString *)tableName {
    return [[self db] columnExists:columnName inTableWithName:tableName];
}

- (NSError *)lastError {
    return [self db].lastError;
}

#pragma mark - Private

- (FMDatabase *)db {
    return [self valueForKey:@"_db"];
}

@end
*/
/**
 RP数据库单例
 */
@interface RPDBManage ()

@property(nonatomic, strong) NSString *dbPath;
@property(nonatomic, weak) FMDatabase *fmdb;
@property(nonatomic, readwrite) FMDatabaseQueue *fmdbQueue;

@end
static RPDBManage *dbManage = nil;
@implementation RPDBManage

+ (instancetype)share {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dbManage = [[RPDBManage alloc] init];
        dbManage.dbPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSLog(@"DB存储地址 == %@", dbManage.dbPath);
        [dbManage createDB];
        [dbManage createBubbleTable];
    });
    return dbManage;
}

+ (void)remove {
    dbManage.fmdb = nil;
    dbManage.fmdbQueue = nil;
    dbManage = nil;
}

- (FMDatabaseQueue *)fmdbQueue {
    if (!_fmdbQueue) {
        NSString *fileName = [self.dbPath stringByAppendingPathComponent:@"local.sqlite"];
        _fmdbQueue = [FMDatabaseQueue databaseQueueWithPath:fileName];
    }
    return _fmdbQueue;
}

- (void)createDB {
//    //设置数据库名称
//    NSString *fileName = [self.dbPath stringByAppendingPathComponent:@"renphoHealth.sqlite"];
//
//    //创建并获取数据库信息
//    self.fmdb = [RPDatabaseQueue databaseQueueWithPath:fileName];
    self.fmdb = [self.fmdbQueue valueForKey:@"_db"];
    
}

- (void)createBubbleTable{
    NSString *sqlStr = @"CREATE TABLE IF NOT EXISTS BubbleTable \
        (user_id varchar(30) NOT NULL, \
        isAgree bool)";
    __unused  BOOL executeUpdate = [self.fmdb executeUpdate:sqlStr];
}


- (void)updateUserName:(NSString *)userName state:(BOOL)state
{
    if(!isValidString(userName)) {
        return;
    }
    NSString *sql  = [NSString stringWithFormat:@"SELECT * FROM BubbleTable WHERE user_id = '%@'" ,userName];
    FMResultSet * set = [self.fmdb executeQuery:sql];

    if (![set next]) {
        __unused BOOL results = [self.fmdb executeUpdate:@"INSERT INTO BubbleTable (user_id, isAgree) VALUES (?,?)",
                                 getValidString(userName),
                                 @(state)];
    }else{
        NSString *sql1  = [NSString stringWithFormat:@"update BubbleTable set isAgree = %@ where user_id = '%@'" ,@(state),getValidString(userName)];
        __unused BOOL update=[self.fmdb executeUpdate:sql1];
    }
}

- (BOOL)queryUserName:(NSString *)userName
{
    if(!isValidString(userName)) {
        return NO;
    }
    
    NSString *sql  = [NSString stringWithFormat:@"SELECT * FROM BubbleTable WHERE user_id = '%@'" ,userName];
    FMResultSet * set = [self.fmdb executeQuery:sql];

    if (![set next]) {
        return NO;
    }
    return YES;
}

- (void)deleteData
{
    NSString *sql  = [NSString stringWithFormat:@"DELETE FROM BubbleTable"];
    BOOL deleate= [self.fmdb executeUpdate:sql];
}
@end
